<template>
    <div data-log-control="返回顶部" @click="backTop" class="scrolltop-btn" v-show="btnFlag">&nbsp;&nbsp;&nbsp;&nbsp;TOP</div>
</template>
<script>
export default {
    props: {
        scrollWrapper: {
            require: true,
        },
        isSmall: {
            type: Boolean,
            require: false,
        }
    },
    data () {
        return {
            btnFlag: false,
        };
    },
    mounted () {
        this.$nextTick(() => {
            if (this.isSmall) {
                let gobackDom = document.getElementsByClassName('scrolltop-btn')[0];
                gobackDom.setAttribute('class', 'btnSmall');
                gobackDom.innerHTML = "TOP";
            }
        });
        this.scrollWrapper.addEventListener("scroll", this.scrollToTop);
    },
    destroyed () {
        this.scrollWrapper.removeEventListener("scroll", this.scrollToTop);
    },
    methods: {
        // 点击图片回到顶部方法，加计时器是为了过渡顺滑
        backTop () {
            let timer = setInterval(() => {
                let ispeed = Math.floor(-this.scrollTop / 5);
                this.scrollWrapper.scrollTop = this.scrollTop + ispeed;
                if (this.scrollTop === 0) {
                    clearInterval(timer);
                }
            }, 16);
        },

        // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
        scrollToTop () {
            let scrollTop = this.scrollWrapper.scrollTop;

            this.scrollTop = scrollTop;
            if (this.scrollTop > 10) {
                this.btnFlag = true;
            } else {
                this.btnFlag = false;
            }
        },
    },
};
</script>
<style scoped lang="scss">
    .btnSmall {
        display: flex;
        align-items: center;
        justify-content: space-around;
        box-sizing: border-box;
        min-width: 50px;
        height: 44px;
        color: #6994FF;
        font-size: 16px;
        border: 2px solid #6994FF;
        opacity: 1;
        border-radius: 6px;
        background: #FFFFFF;
        &:hover {
            cursor: pointer;
            color: #fff;
            background: #6994FF;
        }
    }

.scrolltop-btn {
    display: flex;
    box-sizing: border-box;
    align-items: center;
    justify-content: space-around;
    padding-top: 3px;
    min-width: 80px;
    height: 44px;
    color: #6994FF;
    font-size: 16px;
    border: 2px solid #6994FF;
    opacity: 1;
    border-radius: 6px;
    background: #FFFFFF url("../assets/images/backtotop@2x.png") no-repeat 12px 53%;
    background-size: 18px 20px;
    cursor: pointer;
    &:hover {
        color: #fff;
        background: #6994FF url("../assets/images/backtotop_hover@2x.png") no-repeat 12px 53%;
        background-size: 18px 20px;
    }
}
</style>
